package my.suveng.oauth2.service.auth.impl;

import com.querydsl.jpa.impl.JPAQueryFactory;
import my.suveng.oauth2.service.auth.AuthService;
import my.suveng.oauth2.service.db.mysql.model.entity.QSysUser;
import my.suveng.oauth2.service.db.mysql.model.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 获取登录用户信息
     * 
     * @author suwenguang
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取系统用户
     * 
     * @author suwenguang
     */
    public SysUser getSysUser() {
        Authentication authentication = getAuthentication();
        String username = authentication.getName();
        QSysUser sysUser = QSysUser.sysUser;
        return jpaQueryFactory.selectFrom(sysUser).where(sysUser.username.eq(username)).fetchOne();
    }

    public String getToken() {
        Authentication authentication = getAuthentication();
        return (String) authentication.getPrincipal();
    }
}
